class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            cate: [],
            name: '',
            description: '',
            kc: '',
            price: '',
            goodsunit: '',
            goodssn: '',
            promotional: '',
            id: 0,
            start: 0,
            pagesize: 3,
            fileimgshow: !0,
            imgsrc: '',
            counts: [],
            lbimgsrc: '',
            lbfileimgshow: !0,
            lbimgsrcarr: [],
            tagnamearr: [],
            goodsid: '',
            cid: 0,
            salenum:0,
        };
    }

    submit() {
        var { name, ueditor, kc, imgsrc, price, goodssn, promotional, lbimgsrcarr, goodsunit, description, cid } = this.state, that = this, err = '', imgarr = [];
        // this.setState({ isloading: !0 })

        let reg = /^[0-9]*$/
        if (!ueditor.hasContents()) err = '请输入商品详情';
        if (lbimgsrcarr.length < 1) err = "请添加商品轮播图"
        if (!reg.test(kc)) {
            err = "请输入数字"
        }
        if (kc == "") err = "请输入商品库存"
        //if (goodsunit == "") err = "请输入商品单位"
        if (!Number(promotional)) err = "请输入商品促销价"
        if (!Number(price)) err = "请输入商品原价"
        if (description == "") err = "请输入商品描述"
        if (cid <= 0) err = "请选择分类"
        if (name == "") err = "请输入商品名称"
        if (goodssn == "") err = "请输入商品编号"
        if (!imgsrc) err = "请添加商品图片"
        if (err.length > 0) {
            alert(err);
            return
        }

        imgarr = imgarr.concat(imgsrc, lbimgsrcarr)
        this.uploadimg(imgarr)
    }

    componentDidMount() {
        let UE = window.UE, that = this
        let ueditor = UE.getEditor('ueditor', {
            autoHeightEnabled: true,
            autoFloatEnabled: true
        });
        ueditor.addListener("ready", function () {
            that.setState({ ueditor }, () => {
                let id = GetQueryString('id')
                console.log(id, 'iddididid');
                
                if (id != 'null' && id) {
                    that.setState({ id }, () => {
                        that.freshlist()
                    })
                }
            });
        }, 2);
        GoodsCategetalllist(res => {
            // audiocatempgetlist(res=>{
            if (res.issuccess == 1) {
                // console.log(res.list,'res.data')
                // that.inputlist(res.list);
                var inputhtml = []
                res.list.forEach((x, i) => {
                    inputhtml.push(
                        <div key={i} className="radio"><input type="radio" name="countmethod" value={x.id} id={x.id} /><label for={x.id}></label><span>{x.name}</span></div>
                    )
                })
                that.setState({ inputhtml, cate: res.list })

            }
        })

    }

    freshlist() {
        let { id } = this.state, that = this;
        Goodsfindbyids(id, res => {
            if (res.issuccess == 1) {

                var { ueditor, price, promotional, imgsrc, cid } = this.state, lbhtml = [], lbimgsrcarr = [], x = res.data;
                console.log(x, 'xxxx');
                ueditor.setContent(that.replaceraw(decodeURIComponent(x.detail)))

                price = (x.price / 100).toFixed(2)
                promotional = (x.promotionprice / 100).toFixed(2)

                imgsrc = `${API_HEAD}imgs/${x.topimg}`
                // console.log(imgsrc,'imgsrcimgsrcimgsrc');
                // console.log(x.lbimg,'x.lbimgx.lbimgx.lbimg');
                let lbimgarr = x.lbimg.split(",")
                lbimgarr.forEach((y, i) => {
                    let j = `${API_HEAD}imgs/${y}`
                    lbimgsrcarr.push(j)
                })
                lbimgsrcarr.forEach((x, i) => {
                    lbhtml.push(
                        <div className="img_warp">
                            <img src={x} className="img" />
                            <img className='closeimg' onClick={this.del_lbimg.bind(this, i, x)} src='./src/img_close.png' />
                        </div>
                    )
                })
                cid = x.cid
                $(`input[name=countmethod][value=${cid}]`).prop("checked", "checked");
                this.setState({
                    name: x.name, description: x.description, kc: x.kc, price, imgsrc, fileimgshow: !1,
                    lbfileimgshow: !1, lbhtml, lbimgsrcarr, lburlarr: lbimgsrcarr, goodssn: x.goodssn, promotional,
                    goodsunit: x.goodsunit, cid,salenum:x.salenum
                })
            }
        })

    }
    replaceraw(content) {
        return content.replace('rgb(', 'rgb').replace(new RegExp('rgb', 'g'), "rgb(");
    }
    // inputlist(list) {

    // }

    inputchange(prop, e) {

        this.setState({ [prop]: e.target.value })

    }
    // 图片
    filechangeimg(e) {
        var that = this;
        var filedata = $('#file' + e)[0].files[0];
        let _name, _fileName;
        _name = $('#file' + e)[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            if (e == '3') {
                this.setState({
                    fileimgshow: !1,
                })
            }
            else if (e == '1') {
                this.setState({
                    lbfileimgshow: !1,
                })
            }
            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str], filee)
            }
        }
    }
    putswiperimglistdata(target, e) {
        let { imgsrc, lbimgsrc, lbimgsrcarr } = this.state;
        if (e == '3') {
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${src}`

                }
            }
        }
        else if (e == '1') {
            let lbhtml = []
            target.forEach((x, i) => {
                lbimgsrc = x
                lbimgsrcarr.push(lbimgsrc)
                if (!isBase64(lbimgsrc)) {
                    if (lbimgsrc.indexOf(`${API_HEAD}`) == -1) {
                        lbimgsrc = `${API_HEAD}imgs/${src}`

                    }
                }
            })
            lbimgsrcarr.forEach((x, i) => {
                lbhtml.push(
                    <div className="img_warp">
                        <img src={x} className="img" />
                        <img className='closeimg' onClick={this.del_lbimg.bind(this, i)} src='./src/img_close.png' />
                    </div>
                )
            })
            this.setState({ lbhtml })
        }

        this.setState({
            imgsrc, lbimgsrc, lbimgsrcarr
        })

    }
    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(e) {
        if (e == '3') {
            this.setState({
                imgsrc: '',
                fileimgshow: !0,
            })
        }
    }
    del_lbimg(e) {

        let { lbimgsrcarr } = this.state, lbhtml = [], j = 0
        lbimgsrcarr.forEach((x, i) => {
            if (e == i) {
                lbimgsrcarr.splice(e, 1)
            }
        })
        if (lbimgsrcarr.length == 0) {
            this.setState({ lbhtml: [] })
        } else {
            lbimgsrcarr.forEach((x, i) => {
                lbhtml.push(
                    <div className="img_warp">
                        <img src={x} className="img" />
                        <img className='closeimg' onClick={this.del_lbimg.bind(this, i)} src='./src/img_close.png' />
                    </div>
                )
                this.setState({
                    lbimgsrcarr, lbhtml
                })
            })
        }


    }
    // 上传图片
    uploadimg(arr) {
        let uploadimgarr = [],
            { name, description, ueditor, kc, imgsrc, price, goodssn, promotional, goodsunit, cid,salenum } = this.state, that = this, lbimgarr = [], imgarr = [], html = ueditor.getContent();
        arr.forEach((x, i) => {
            if (i == 0) {
                if (x.indexOf(`${API_HEAD}`) == -1) {
                    if (isBase64(x)) {
                        uploadimg(x, res => {
                            if (res.issuccess == 1) {
                                x = `${API_HEAD}imgs/${res.path}`
                                uploadimgarr.push(x)
                            } else {
                                alert(res.msg)
                                err = 1
                                return;
                            }
                        })
                    }
                } else {
                    uploadimgarr.push(x)
                }
                console.log(x, 'xxxxxxx');

            } else {
                if (x.indexOf(`${API_HEAD}`) == -1) {
                    if (isBase64(x)) {
                        uploadimg(x, res => {
                            if (res.issuccess == 1) {
                                x = `${API_HEAD}imgs/${res.path}`
                                uploadimgarr.push(x)
                            } else {
                                alert(res.msg)
                                err = 1
                                return;
                            }
                        })
                    }
                } else {
                    uploadimgarr.push(x)
                }
            }
        })
        if (uploadimgarr.length == arr.length) {
            uploadimgarr.forEach((x, i) => {
                if (i == 0) {
                    imgsrc = x.replace(`${API_HEAD}imgs/`, '')
                } else {
                    let lb = x.replace(`${API_HEAD}imgs/`, '')
                    lbimgarr.push(lb)
                }
            })
            let lbimg = String(lbimgarr)
            var data = {
                name, description, kc, topimg: imgsrc, detail: that.replaceraw(encodeURIComponent(html)), price: Math.ceil(Number(price) * 100), goodssn,
                promotionprice: Math.ceil(Number(promotional) * 100), goodsunit, lbimg, cid,salenum
            }
            if (this.state.id > 0) data['id'] = this.state.id;
            console.log(data, 'data')
            Goodsaoegoods(data, res => {
                this.setState({ showloading: '' })
                // this.setState({ isloading: !1 })
                if (res.issuccess == 1) {
                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    window.location.href = "./goods.html";
                } else {
                    alert(res.msg)
                }
            })
        }
    }

    toback() {
        window.location.href = "./goods.html";
    }

    render() {
        let { inputhtml, name, imgsrc, kc, description, price, lbhtml, goodsunit, goodssn, promotional,salenum } = this.state;

        return (
            <div className="breadLinebox">
                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">
                        <span>当前目录</span> > <span onClick={this.toback.bind(this)} style={{ cursor: 'pointer' }}>优选购管理</span> > {this.state.id > 0 ? "编辑" : "新建"}优选购
                    </div>
                    <div className="content form">
                        <div className="formtitle">
                            <p>{this.state.id > 0 ? "编辑" : "新建"}</p>
                        </div>
                        <div className="formbox">
                            <div className="formcontent">
                                <div className="input-group">
                                    <span className="label input-group-addon">商品图片</span>
                                    <input onChange={this.filechangeimg.bind(this, '3')} type='file' id='file3' style={{ display: "none" }} />
                                    <div className=''>
                                        <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, '3')} style={{ display: this.state.fileimgshow ? "" : "none" }} />
                                        <div className="img_warp" style={{ display: this.state.fileimgshow ? "none" : "" }}>
                                            <img src={imgsrc} className="img" />
                                            <img className='closeimg' onClick={this.del_img.bind(this, '3')} src='./src/img_close.png' style={{ display: this.state.fileimgshow ? "none" : "" }} />
                                        </div>
                                    </div>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">商品编号</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'goodssn')} value={goodssn} type="text" placeholder='请输入商品编号' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">商品名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'name')} value={name} type="text" placeholder='请输入名称' className="input" />
                                </div>
                                <div className="input-group countrys">
                                    <span className="input-group-addon">音频分类</span>
                                    <div className="countryname" onChange={this.inputchange.bind(this, 'cid')}>
                                        {inputhtml}
                                    </div>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">商品描述</span>
                                    <textarea id='describe' onChange={this.inputchange.bind(this, 'description')} value={description} className="textarea" placeholder='请输入描述' rows="5"></textarea>
                                </div>
                                <div>
                                    <div className="input-group inline">
                                        <span className="input-group-addon">原价</span>
                                        <input id='name' onChange={this.inputchange.bind(this, 'price')} value={price} type="text" placeholder='请输入商品原价' className="input" />
                                    </div>
                                    <div className="input-group inline">
                                        <span className="input-group-addon">促销价</span>
                                        <input id='name' onChange={this.inputchange.bind(this, 'promotional')} value={promotional} type="text" placeholder='请输入商品促销价' className="input" />
                                    </div>
                                    <div className="input-group inline">
                                        <span className="input-group-addon">商品单位</span>
                                        <input id='name' onChange={this.inputchange.bind(this, 'goodsunit')} value={goodsunit} type="text" placeholder='请输入商品单位 如：件' className="input" />
                                    </div>
                                    <div className="input-group inline">
                                        <span className="input-group-addon">库存</span>
                                        <input id='name' onChange={this.inputchange.bind(this, 'kc')} value={kc} type="text" placeholder='请输入商品库存' className="input" />
                                    </div>
                                    <div className="input-group inline">
                                        <span className="input-group-addon">销量</span>
                                        <input id='name' onChange={this.inputchange.bind(this, 'salenum')} value={salenum} type="text" placeholder='请输入商品销量' className="input" />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <p className="lbtit"><span className="label input-group-addon">商品轮播</span><span className="red">(375 x 300)</span></p>
                                    <input onChange={this.filechangeimg.bind(this, '1')} type='file' id='file1' style={{ display: "none" }} />
                                    <div className='detail_btns lbimgbox'>
                                        <div>
                                            {lbhtml}
                                        </div>
                                        <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, '1')} />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">富文本</span>
                                    <textarea id={'ueditor'} style={{ height: "30vh" }} ></textarea>
                                </div>

                                <div className='submitbox'>
                                    <button type="button" onClick={this.submit.bind(this)} className="submitbutton">保存</button>
                                    <button type="button" onClick={this.toback.bind(this)} className="submitbutton" style={{ marginLeft: '100' }}>返回</button>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>





        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='goods' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)
